package review.data.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import review.config.Constants;
import review.dao.ScienceDAO;
import review.entity.Science;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
@Transactional
public class ScienceServiceImpl implements ScienceService {

  @Autowired
  private ScienceDAO scienceDAO;

  // 添加专业
  public void addScience(Science science) {
    if (!StringUtils.hasText(science.getName())) {
      throw new RuntimeException("专业名称不能为空");
    }
    Science scExample = new Science();
    scExample.setName(science.getName());
    scExample.setParent(science.getParent());
    Example<Science> example = Example.of(scExample);
    if (scienceDAO.exists(example)) {
      throw new RuntimeException("专业名称不能重复");
    }
    scienceDAO.save(science);
    science.setOrderIndex(science.getId());
  }

  // 判断id或名称是否存在
  public Science judge(Science science) {
    if (scienceDAO.findByName(science.getName()) == null) {
      Optional<Science> o = scienceDAO.findById(science.getId());
      if (!o.isPresent()) {
        throw new RuntimeException("ID或专业名称不存在");
      } else {
        return o.get();
      }
    } else {
      return scienceDAO.findByName(science.getName());
    }
  }

  // 修改专业
  public void updateScience(Science science) {
    if (!StringUtils.hasText(science.getName())) {
      if (science.getId() == null) {
        throw new RuntimeException("专业名称或Id为空");
      }
    }
    Science sc = judge(science);
    science.setParent(sc.getParent());
    science.setOrderIndex(sc.getOrderIndex());
    science.setId(sc.getId());
    scienceDAO.save(science);
  }

  // 删除专业
  public void deleteScience(Science science) {
    if (!StringUtils.hasText(science.getName())) {
      throw new RuntimeException("专业名为空");
    }
    Science sc = scienceDAO.findByName(science.getName());
    if (sc == null) {
      throw new RuntimeException("该专业不存在");
    }
    // 判断是否有下属专业
    if (!scienceDAO.findAllByParent(sc.getId()).isEmpty()) {
      throw new RuntimeException("该专业有下属专业无法删除");
    }
    scienceDAO.delete(sc);
  }

  // 分页查询全部专业
  public List<Science> findAll() {
    Sort sort = Sort.by(Direction.ASC, "orderIndex");
    List<Science> list = scienceDAO.findAll(sort);
    return list;
  }

  public JSONObject transformJSON(List<Science> sciences) {
    JSONArray jsonArray = new JSONArray();
    for (Science sc : sciences) {
      // 判断是否为最顶级专业
      if (sc.getParent() == null) {
        JSONObject obj = getJSONobject(sc);
        JSONArray objects = getScienceJson(sc.getId(), sciences);
        if (!objects.isEmpty()) {
          obj.put("children", objects);
        }
        jsonArray.add(obj);
      }
    }

    JSONObject object = new JSONObject();
    object.put(Constants.DATA, jsonArray);
    object.put(Constants.SUCCESS, true);
    object.put(Constants.CODE, true);
    object.put(Constants.MSG, "");
    return object;
  }

  // 递归处理
  public JSONArray getScienceJson(Integer id, List<Science> list) {

    // 当前层级当前点下的所有子节点
    List<Science> childList = getChildScience(id, list);
    JSONArray childTree = new JSONArray();
    for (Science science : childList) {
      JSONObject object = getJSONobject(science);
      JSONArray childs = getScienceJson(science.getId(), list);
      if (!childs.isEmpty()) {
        object.put("children", childs);
      }
      childTree.fluentAdd(object);
    }
    return childTree;
  }

  // 获取当前节点的所有子节点
  public List<Science> getChildScience(Integer id, List<Science> list) {
    List<Science> sciences = new ArrayList<>();
    for (Science sc : list) {
      if (sc.getParent() != null && sc.getParent().intValue() == id) {

        sciences.add(sc);
      }
    }
    return sciences;
  }

  // 构建JSON
  public JSONObject getJSONobject(Science science) {
    JSONObject object = new JSONObject();
    object.put("value", science.getId());
    object.put("label", science.getName());

    return object;
  }

  // 分页模糊查询
  public Page<Science> findAll(int page, int size, Science sc) {
    ExampleMatcher matcher = ExampleMatcher.matching().withIgnoreNullValues().withMatcher("name",
        ExampleMatcher.GenericPropertyMatchers.contains());
    Example<Science> example = Example.of(sc, matcher);
    Pageable pageable = PageRequest.of(page - 1, size, Sort.by(Sort.Direction.ASC, "parent", "orderIndex"));
    return scienceDAO.findAll(example, pageable);
  }

}
